<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
              <a-form-item name="projectName">
                <template #label><span title="项目名称">项目名称</span></template>
                <a-input placeholder="请输入项目名称" v-model:value="queryParam.projectName" allow-clear ></a-input>
              </a-form-item>
            </a-col>
          <a-col :lg="6">
            <a-form-item name="projectId">
              <template #label><span title="主项目">主项目</span></template>
              <j-select-multiple placeholder="请选择主项目" v-model:value="queryParam.projectId" dictCode="c_project_application,project_name,id" allow-clear />
            </a-form-item>
          </a-col>

           <a-col :lg="6">
              <a-form-item name="title">
                <template #label><span title="标题">标题</span></template>
                <a-input placeholder="请输入标题" v-model:value="queryParam.title" allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="projectNumber">
                <template #label><span title="项目编号">项目编号</span></template>
                <a-input placeholder="请输入项目编号" v-model:value="queryParam.projectNumber" allow-clear ></a-input>
              </a-form-item>
            </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'crm:c_additional_request:add'"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button  type="primary" v-auth="'crm:c_additional_request:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
		
<!--        <j-upload-button  type="primary" v-auth="'crm:c_additional_request:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>-->
       <a-space  v-auth="'crm:c_additional_request:ocr'" >
         <j-upload  @success="handleUploadSuccess"    text="需求ocr导入"  v-model:fileList="fileList" ></j-upload>
       </a-space>

        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'crm:c_additional_request:deleteBatch'">批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
       
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <template v-slot:bodyCell="{ column, record, index, text }">
         <template v-if="column.key === 'title'">
            <router-link  tag="li" :to="{path: '/projectquote/CProjectQuoteAdditionalList', query: { additionalId: record.id} }">
              {{ record.title }}
            </router-link>
		  </template>

        <template v-if="column.dataIndex==='appendix'">
        <!--文件字段回显插槽-->
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small"
                    @click="handleViewFile(text)">查看</a-button>
        </template>

        <template v-if="column.dataIndex==='quoteRecord'">
          <a href="#" @click="clickQuoteRecord(record)" >{{record.quoteRecord}}</a>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <CAdditionalRequestModal ref="registerModal" @success="handleSuccess"></CAdditionalRequestModal>
    <CSubProjectModal ref="projectRegisterModal" @success="handleSuccess"></CSubProjectModal>
   <CProjectQuoteAdditionalModalModal ref="projectQuoteRegisterModal" @success="handleSuccess"></CProjectQuoteAdditionalModalModal>

    <!-- 报价记录-->
     <ProjectQuoteTable @register="registerDrawer" />
      <!-- 引入 ViewFileDetail 组件 -->
    <ViewFileDetail ref="viewFileDetailRef" @view-file="viewFileDetail = $event"></ViewFileDetail>
  </div>
</template>

<script lang="ts" name="crm-cAdditionalRequest" setup>
  import { ref, reactive,defineComponent } from 'vue';
   import { useDrawer } from '/@/components/Drawer';
  import ProjectQuoteTable from '../projectquote/CProjectQuoteTable.vue'
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './CAdditionalRequest.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    getOcrAdditional,
    findSubProjectById, postStartQuote
  } from "./CAdditionalRequest.api";

  import { downloadFile } from '/@/utils/common/renderUtils';
  import CAdditionalRequestModal from './components/CAdditionalRequestModal.vue'
  import CProjectQuoteAdditionalModalModal from '../projectquote/components/CProjectQuoteAdditionalModal.vue'
  import CSubProjectModal from '../subproject/components/CSubProjectModal.vue'
  import { useUserStore } from '/@/store/modules/user';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import RecordList from "@/views/companyinfodetails/CCompanyInfoDetailTable.vue";
  import ViewFileDetail from "@/components/FileView/ViewFileDetail.vue";
  import JSelectMultiple from "@/components/Form/src/jeecg/components/JSelectMultiple.vue";
  const registerModal = ref();
      //弹框
  //弹框
  const [registerDrawer, { openDrawer }] = useDrawer();


  // 从子组件获取 viewFileDetail 方法
  const viewFileDetail = ref();
  const viewFileDetailRef = ref();
  // 在 table 的插槽中使用 viewFileDetail 方法
  function handleViewFile(url) {
    viewFileDetail.value(url);
  }


 const { createMessage } = useMessage();
  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);

  const projectRegisterModal = ref();
  const projectQuoteRegisterModal = ref();

  const userStore = useUserStore();
   const fileList = ref([]);
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '增项需求表',
      api: list,
      columns,
      canResize:false,
      useSearchForm: false,
      actionColumn: {
        width: 180,
        fixed: 'right',
      },
      beforeFetch: async (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: "增项需求表",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

 
 //生成子项目
  function addSubProject(record: Recordable) {
    const params = {
      "projectNumber":record.projectNumber,
      "subProjectName":record.projectName,
      "subProjectDescription":record.applicationContent,
      "attachmentUrl":record.appendix,
      "additionalId":record.id,
      "projectId":record.projectId,

    }
    projectRegisterModal.value.disableSubmit = false;
    projectRegisterModal.value.addSubProject(params);
  }
  //查看主项目
  async function projectHandleEdit(record: Recordable) {
    const param = {"id":record.subProjectId}
    const projectRecord = await findSubProjectById(param)

    projectRegisterModal.value.disableSubmit = false;
    projectRegisterModal.value.edit(projectRecord);
  }




  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add({});
  }
  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
   
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
   
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
   
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  function getDropDownAction(record) {
    return [
      {
         label: '详情',
        onClick: handleDetail.bind(null, record),
      }, {
         label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'crm:c_additional_request:edit'
      }
    ]
  }

  /**
   * 开始报价
   * @param record
   */
 async function startQuote(record: Recordable){
    await postStartQuote({ id: record.id }, handleSuccess);
  }
   /**
   * 报价
   * @param record
   */
 async function projectQuote(record: Recordable) {
    const params = {
      "additionalId":record.id,
    }
    projectQuoteRegisterModal.value.disableSubmit = false;
    projectQuoteRegisterModal.value.add(params);
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    const data = [{}]
   if(record.status ==="创建成功" || record.status ===""  ){
      data.push(
        {
          label: '开始报价',
          onClick: startQuote.bind(null, record),
          auth: 'crm:c_additional_request:generator'
        },
      )
    }else if(record.status ==="报价中" ){
      data.push(
        {
          label: '报价',
          onClick: projectQuote.bind(null, record),
           auth: 'crm:c_additional_request:quote'
        },
      )
    }
   if(record.status ==="报价中" ){
      data.push(
        {
          label: '生成子项目',
          onClick: addSubProject.bind(null, record),
          auth: 'crm:c_additional_request:generator'
        },
      )
    }
   if(record.status ==="成立") {
      data.push(
        {
          label: '查看子项目',
          onClick: projectHandleEdit.bind(null, record),
          auth: 'crm:c_additional_request:generator'
        },
      )
    }

    return data;
  }


  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
  
  
  async function handleUploadSuccess(response: any, file: any) {
  	try {
  		  const param = {'filePath':response.message}
  		  const resultData = await getOcrAdditional(param);
  		   if (resultData && resultData.length > 0) {
			   debugger
  			   fileList.value.splice(0, 1);
  			   createMessage.success("识别完成");
  			   
  			   const result = resultData[0]
  			   const formData = reactive<Record<string, any>>({
  				 title: result['标题'],
  				 projectNumber: result['项目编号'],
				 applicant: result['申请人'],
				 applicationDate: result['申请日期'],
				 department: result['所属部门'],
				 projectName: result['项目名称'],
				 warehouse: result['仓库'],
				 requestType: result['需求类型'],
				 expectFulfillData: result['期望完成日期'],
				 predictFulfillData: result['预计完成日期'],
				 priority: result['优先级'],
				 directMaintenance: result['直接维修'],
				 purchaseModel: result['品牌、型号(采购适用)'],
				 purchaseQuantity: result['数量(采购适用)'],
				 purchaseEstimatedCost: result['预估费用(设备部填写)'],
				 applicationReason: result['申请原因'],
				 applicationContent: result['申请内容'],
				 acceptingClaim: result['维修/维保服务验收要求'],
  				 appendix: response.message,  
  			   });
  			   createMessage.success("读取成功");
  			   registerModal.value.disableSubmitOk = false;
  			   registerModal.value.disableSubmit = false;
  			   registerModal.value.add(formData);
  			}
  		} catch (error) {
  			fileList.value.splice(0, 1);
  			createMessage.warning('识别失败:');
  		}
  	   
  	}
  	
  function clickQuoteRecord(record){
    openDrawer(true, record);
  }



</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }
</style>
